package org.basis.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * 第一版可写server
 *
 * @author Mr_wenpan@163.com 2021/09/15 10:14
 */
@Slf4j
public class WriteServer1 {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        log.info("server端启动完毕......");

        while (true) {
            // 阻塞等待事件发生
            selector.select();
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();

                // accept事件
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.info("接收到客户端连接，客户端地址：{}", sc.getRemoteAddress());

                    // 1.sc注册后向客户端发送大量的数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }
                    // 将字符串转为buffer
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());

                    // 2.返回值代表实际写入的字节数[这里可能一次将buffer里的数据发送不完，所以就要分多次发]
                    while (buffer.hasRemaining()) {
                        // buffer --> channel的内部空间
                        int write = sc.write(buffer);
                        System.out.println("写入字节数：" + write);
                    }
                }
            }
        }
    }
}
